package com.walle.concurrenttest.pattern.balking;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author zhangjiapeng
 * @Package com.walle.concurrenttest.pattern.balking
 * @Description: ${todo}
 * @date 2019/2/19 11:11
 */
public class Data {

    private final String fileName;

    private String content;

    private boolean changed;

    public Data(String fileName) {
        this.fileName = fileName;
    }

    public synchronized void change(String content){
        this.changed = true;
        this.content = content;
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + "修改文件内容");
        notifyAll();
    }

    public synchronized void save(){
        String threadName = Thread.currentThread().getName();
        if(changed){
            doSave();
            changed = false;
            System.out.println(threadName + "保存修改文件内容");
        }else{
            System.out.println(threadName + "文件未修改，放弃保存");
            return;
        }
    }

    private void doSave(){
        BufferedWriter writer = null;
        try {
            Path path = Paths.get(fileName);
            if(Files.notExists(path)){
                Files.createFile(path);
            }
            writer = Files.newBufferedWriter(path);
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


}
